<template>
  <div class="app-container">
    <div class="container-bg">
      <el-row :gutter="15">
        <el-col :span="12"  v-loading="tableLoading">
          <el-form
            style="margin-top: 20px"
            :model="tab5form"
            ref="ruleForm"
            label-width="150px"
            :rules="rules"
          >
            <!-- <el-col :span="18">
                <el-form-item label="门禁类型" prop="online">
                <el-select
                  v-model="tab5form.online"
                  @change="handleSelectChange"
                  type="number"
                  placeholder="请选择"
                  >
                  <el-option label="云门禁" :value="1"></el-option>
                  <el-option label="PC门禁" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="18">
              <el-form-item label="门禁类型" prop="online">
                <el-radio-group v-model="tab5form.online">
                    <el-radio :label="1">云门禁</el-radio>
                    <el-radio :label="0">PC门禁</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
            <el-col :span="18">
              <el-form-item label="导入证书" size="large">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  accept=".zip"
                  :count='1'
                  :auto-upload="false"
                  :on-change="getFile"
                  ref="uploadImg"
                  :show-file-list="false"
                >
                  <template slot="trigger">
                    <el-button type="primary">上传</el-button>
                  </template>
                  <el-button type="primary" plain icon="el-icon-refresh" @click="getPluginApi" style="margin-left: 10px;">刷新</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="服务器地址" prop="addr">
                <el-input
                  v-model="tab5form.addr"
                  placeholder="请输入服务器地址"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="端口" prop="port">
                <el-input-number
                  class="textleft"
                  v-model="tab5form.port"
                  controls-position="right"
                  :min="200"
                  :max="65535"
                  label="请输入端口"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="tls验证" prop="mqttTls">
                <el-select
                  v-model="tab5form.mqttTls"
                  type="number"
                  placeholder="请选择"
                  :disabled="true"
                  >
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="关闭" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="设备序列号" prop="serialNumber">
                <el-input
                  v-model="tab5form.serialNumber"
                  placeholder="请输入设备序列号"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="设备代码" prop="deviceCode">
                <el-input
                  v-model="tab5form.deviceCode"
                  placeholder="请输入设备代码"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="用户名" prop="mqttUsername">
                <el-input
                  v-model="tab5form.mqttUsername"
                  placeholder="请输入用户名"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="密码" prop="mqttPassword">
                <el-input
                  v-model="tab5form.mqttPassword"
                  placeholder="请输入密码"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="设备密匙" prop="deviceSecret">
                <el-input
                  v-model="tab5form.deviceSecret"
                  placeholder="请输入设备密匙"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="产品密匙" prop="productKey">
                <el-input
                  v-model="tab5form.productKey"
                  placeholder="请输入产品密匙"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="minioUrl" prop="minioUrl">
                <el-input
                  v-model="tab5form.minioUrl"
                  placeholder="请输入minioUrl"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="minioId" prop="minioId">
                <el-input
                  v-model="tab5form.minioId"
                  placeholder="请输入minioId"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="minioSecret" prop="minioSecret">
                <el-input
                  v-model="tab5form.minioSecret"
                  placeholder="请输入minioSecret"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18" v-if="isAdmin">
              <el-form-item size="large">
                <el-button type="primary" @click="onSubmit('ruleForm')">保存</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-col>
        <el-col :span="12" v-loading="table2Loading">
          <el-form
            style="margin-top: 20px"
            element-loading-text="Loading"
            :model="pluginform"
            id="pluginform"
            label-width="150px"
          >
            <el-col :span="18">
              <el-form-item label="插件名称" prop="plugins_name">
                 <!-- v-model="pluginform.plugins_name" -->
                <el-input
                  v-model="pluginform.plugins_name"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="插件版本" prop="plugins_version">
                <el-input
                  v-model="pluginform.plugins_version"
                  class="color000"
                  :disabled="true"
                  clearable
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="18">
              <el-form-item label="网络连接状态" prop="socket_state">
                <el-input
                  v-model="pluginform.socket_state"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="18">
              <el-form-item label="最后上传时间" prop="last_upload_time">
                <el-input
                  v-model="pluginform.last_upload_time"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="18">
              <el-form-item label="插件启动时间" prop="plugins_load_time">
                <el-input
                  v-model="pluginform.plugins_load_time"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col> -->

            <el-col :span="18">
              <el-form-item label="Minio状态" prop="minio">
                <el-input
                  v-model="pluginform.minio"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="Mqtt状态" prop="mqtt">
                <el-input
                  v-model="pluginform.mqtt"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="上传成功" prop="minio_sucess_count">
                <el-input
                  v-model="pluginform.minio_sucess_count"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="上传失败" prop="minio_fail_count">
                <el-input
                  v-model="pluginform.minio_fail_count"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="请求超时" prop="post_timeout_count">
                <el-input
                  v-model="pluginform.post_timeout_count"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="应答个数" prop="recv_packet_count">
                <el-input
                  v-model="pluginform.recv_packet_count"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="请求个数" prop="send_packet_count">
                <el-input
                  v-model="pluginform.send_packet_count"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="启动时间" prop="uptime">
                <el-input
                  v-model="pluginform.uptime"
                  class="color000"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="18">
              <el-form-item size="large">
                <el-button type="primary" plain icon="el-icon-refresh" @click="getPlugin2Api">刷新</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getPluginConfig, setPluginConfig, getPluginStatus } from "@/api/network";
import { fileUploadApi } from "@/api/community/person";
  import axios from 'axios';
  import { getToken } from "@/utils/auth";
  import Cookies from "js-cookie";
  import $ from 'jquery';

  export default {
    name: "MvCloudgateTerminalThirdPlatform",

    data() {
      var validatePort = (rule, value, callback) => {
        if (value === "") {
          callback(new Error('端口不能为空'));
        } else {
          if (!(value >= 1 && value <= 65535)) {
            callback(new Error('端口须在1-65535之间'));
          }
          callback();
        }
      };
      return {
        activeValue: 0,
        inactiveValue: 1,
        isAdmin:false,
        formPrev: {},
        tableLoading:false,
        table2Loading:false,
        tab5form: {
          addr: null,
          port: "",
          // online: "",
          mqttTls: "",
          serialNumber: "",
          deviceCode: "",
          mqttUsername: "",
          mqttPassword: "",
          deviceSecret: "",
          productKey: "",
          minioUrl: "",
          minioId: "",
          minioSecret: "",
        },
        pluginform: {
          plugins_name: "",
          plugins_version: "",
          // socket_state: "",
          login_state: "",
          // last_upload_time: "",
          // plugins_load_time: "",
          minio: "",
          mqtt: "",
          minio_sucess_count: "",
          minio_fail_count: "",
          post_timeout_count: "",
          recv_packet_count: "",
          send_packet_count: "",
          uptime: ""
        },
        rules: {
          addr: [
            {required: true, message: "服务器地址不能为空", trigger: "blur"},
            {max: 128, message: "服务器地址不能超过128位", trigger: "blur"},
          ],
          port: [
            {required: true, message: "端口不能为空", trigger: "blur"},
            { validator: validatePort, trigger: 'blur' },
            { pattern:/^[0-9]*$/, trigger: "blur", message: '请输入正整数' },
          ],
          minioUrl: [
            {required: true, message: "minioUrl不能为空", trigger: "blur"},
            {max: 128, message: "minioUrl不能超过128位", trigger: "blur"},
          ],
          minioId: [
            {required: true, message: "minioId不能为空", trigger: "blur"},
            {max: 128, message: "minioId不能超过128位", trigger: "blur"},
          ],
          minioSecret: [
            {required: true, message: "minioSecret不能为空", trigger: "blur"},
            {max: 128, message: "minioSecret不能超过128位", trigger: "blur"},
          ],
        },
        minioStatusMap: {
          0: '连接成功',
          1: '连接失败'
        },
        mqttStatusMap: {
          200: '注册成功',
          8000: '正在连接',
          8001: 'Mqtt连接成功',
          8002: 'Mqtt连接断开',
          8003: 'Tcp连接成功',
          8004: 'Tcp连接失败',
          8005: '协议连接失败',
        }
      };
    },
    created() {
      this.getPluginApi();
      this.getPlugin2Api();
    },
    mounted() {
      this.$nextTick(()=>{
        this.isAdmin=Cookies.get('roleId')=='0'?true:false
      })
    },
    methods: {
      getFile(file) {
        const params = new FormData();
        params.append("fileType", 99);
        params.append("fileData", file.raw)

        if (file.size / 1024 / 1024 > 1) {
          this.$message.error("最大不超过1m!")
          return false;
        }
        fileUploadApi(params).then(res => {
          console.log('fileUploadApi：', res)
          this.getPluginApi()
          if (res) {
            // item.url = URL.createObjectURL(file.raw)
            this.$message.success("上传成功")
          }
        })
      },
      handleSelectChange() {
        this.$forceUpdate()
      },
      getPluginApi: function() {
        let self = this;
        getPluginConfig().then(res=>{
          console.log(295,res);

          res.deviceSecret = res.deviceSecret?.length > 0 && res.deviceSecret.replace(/./g, '*')
          res.productKey = res.productKey?.length > 0 && res.productKey.replace(/./g, '*')
          res.minioId = res.minioId?.length > 0 && res.minioId.replace(/./g, '*')
          res.minioSecret = res.minioSecret?.length > 0 && res.minioSecret.replace(/./g, '*')

          self.tab5form = res;
          // self.tab5form.online = (!res.data.online && res.data.online != 0) ? 0 : res.data.online;
          // self.formPrev = JSON.parse(JSON.stringify(res));
          console.log(156,self.tab5form);
        },err =>{
          console.log(err)
        })
        .catch(error =>{
          console.log(error);
        })
      },
      getPlugin2Api: function() {
        this.table2Loading = true;
        let self = this;
        setTimeout(function () {
          getPluginStatus({plugin_name: self.tab5form.plugins_name}).then(res=>{
            console.log(348,res);
            if (res.data != 'error') {
              self.pluginform = res;
              // self.pluginform.socket_state = self.pluginform.socket_state == 0 ? '成功' : '失败';
              self.pluginform.minio = self.pluginform.minio ? '连接成功' : '连接失败';
              self.pluginform.mqtt = self.mqttStatusMap[self.pluginform.mqtt] || `注册失败-${self.pluginform.mqtt}`;
            }
            self.table2Loading = false;
          },err =>{
            console.log(err)
            self.table2Loading = false;
          })
          .catch(error =>{
            console.log(error);
            self.table2Loading = false;
          })
        }, 100);
      },
      onSubmit(formName) {
        this.tableLoading = true
        this.$refs[formName].validate((valid) => {
          console.log(valid, 'valid')
          if (valid) {
            this.tab5form.port = this.tab5form.port*1;
            const params = {
              addr: this.tab5form.addr,
              port: this.tab5form.port,
              // mqttTls: this.tab5form.mqttTls,
              // minioUrl: this.tab5form.minioUrl,
              // minioId: this.tab5form.minioId,
              // minioSecret: this.tab5form.minioSecret
            }

            setPluginConfig(params).then(res=>{
              // console.log(184,res);
              // if (res.statusText == 'OK') {
                this.$message.success("保存成功");
                this.tableLoading = false
              // } else {
              //   this.$message.error("保存失败");
              // }
            },err =>{
              console.log(err)
              this.$message.error("保存失败");
              this.tableLoading = false
            })
            .catch(error =>{
              console.log(error);
              this.$message.error("保存失败");
              this.tableLoading = false
            })

            console.log(391, this.formPrev, this.tab5form);
            // if (JSON.stringify(this.formPrev) === JSON.stringify(this.tab5form)) {
            //   return false;
            // } else {
            // this.formPrev = JSON.parse(JSON.stringify(this.tab5form));
            // let self = this;
            // setTimeout(function () {
            //   axios({
            //     headers: {
            //       Authorization: "Bearer " + getToken()
            //     },
            //     method: "post",
            //     url: "http://"+location.hostname+"/params/",
            //     timeout: 10000,
            //     data: {
            //       method: 'restart_plugin',
            //       params: {}
            //     }
            //   }).then(res=>{
            //     console.log(408,res);
            //     if (res.data == 'ok') {
            //       // self.$message.success("操作成功");
            //     } else {
            //       // self.$message.error("操作失败");
            //     }
            //   },err =>{
            //     console.log(err)
            //   })
            //   .catch(error =>{
            //     console.log(error);
            //   })
            // }, 1000);
          }
          // }
        });
      }

    },
  };
</script>

<style lang="scss" scoped>
    .container-bg {
      max-width: 1600px;
    }
    .textleft {
      width: 100%;
    }
    // /deep/ .el-loading-mask {
    //   margin-top: 40%;
    // }
    /deep/ .textleft .el-input--medium input {
      text-align: left;
    }
    /deep/ .el-select {
      width: 100%;
    }
    /deep/ .el-input.is-disabled .el-input__inner {
      color: #000 !important;
    }
</style>
